package com.hkbigdata.cryd.java.ai.langchain4j.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkbigdata.cryd.java.ai.langchain4j.entity.Appointment;
import com.hkbigdata.cryd.java.ai.langchain4j.exception.DuplicateAppointmentException;
import com.hkbigdata.cryd.java.ai.langchain4j.mapper.AppointmentMapper;
import com.hkbigdata.cryd.java.ai.langchain4j.service.AppointmentService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, Appointment>
        implements AppointmentService {

    @Override
    public Appointment getOne(Appointment appointment) {
        LambdaQueryWrapper<Appointment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Appointment::getUsername, appointment.getUsername())
                .eq(Appointment::getIdCard, appointment.getIdCard())
                .eq(Appointment::getDepartment, appointment.getDepartment())
                .eq(Appointment::getDate, appointment.getDate())
                .eq(Appointment::getTime, appointment.getTime());

        // 显式限制查询结果数量
        queryWrapper.last("LIMIT 2");
        List<Appointment> results = baseMapper.selectList(queryWrapper);

        if (CollectionUtils.isEmpty(results)) {
            return null;
        } else if (results.size() > 1) {
            throw new IllegalStateException("存在多条重复预约记录，请检查数据一致性");
        }
        return results.get(0);
    }

    @Override
    @Transactional
    public boolean save(Appointment entity) {
        try {
            // 尝试直接保存，依赖数据库唯一索引
            return super.save(entity);
        } catch (DuplicateKeyException e) {
            // 捕获数据库唯一索引异常
            Appointment existing = getOne(entity);
            if (existing != null) {
                throw new DuplicateAppointmentException("该时段已存在预约，不可重复创建");
            }
            // 处理其他可能的唯一键冲突
            throw new IllegalStateException("预约创建失败，请稍后重试", e);
        }
    }
}